package com.yy.wga.common.util.aop;

import com.yy.wga.common.core.enmus.EResponseCode;
import com.yy.wga.common.core.exception.BusinessException;
import com.yy.wga.common.util.SpelUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

/**
 * 分布式锁注解实现
 *
 * @author lgw
 */
@Aspect
@Slf4j
public class DistributedLockAspect {

    @Resource
    private RedissonClient redissonClient;

    @Around("@annotation(lockAnnotation)")
    public Object around(ProceedingJoinPoint joinPoint, DistributedLock lockAnnotation) throws Throwable {
        String lockName = "LOCK_KEY:" + SpelUtils.getSpelValue(lockAnnotation.value(), joinPoint);
        RLock lock = redissonClient.getLock(lockName);

        try {
            boolean isLocked = lock.tryLock(lockAnnotation.waitTime(), lockAnnotation.leaseTime(), TimeUnit.SECONDS);
            if (isLocked) {
                return joinPoint.proceed();
            } else {
                throw new BusinessException(EResponseCode.REPEATED_REQUEST);
            }
        } finally {
            if (lock.isLocked()) {
                lock.unlock();
            }
        }
    }
}
